package com.zx.framework.core.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理cookie的工具类
 * @author stylewolf
 *
 */
public class CookieUtil {
	/**
	 * 添加cookie
	 * @param key
	 * @param value
	 * @param age -1值表示关闭浏览器删除 0表示立即删除
	 * @param response
	 */
	public static void addCookie(String key,String value,int age,HttpServletResponse response){
		Cookie cookie = new Cookie(key,value);
		cookie.setPath("/"); 
		cookie.setMaxAge(age);
		response.addCookie(cookie);
	}
	/**
	 * 获取cookie
	 * @param key
	 * @param request
	 * @return
	 */
	public static Cookie getCookie(String key,HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		Cookie cookie = null;
		if(cookies==null){
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			cookie = cookies[i];
			if(cookie.getName().equals(key)){
				return cookie;
			}
		}
		return null;
	}
	/**
	 * 获取cookie的值
	 * @param key
	 * @param request
	 * @return
	 */
	public static String getCookieValue(String key,HttpServletRequest request){
		Cookie cookie = getCookie(key, request);
		if(cookie==null){
			return "";
		}
		return cookie.getValue();
	}
	/**
	 * 删除cookie
	 * @param key
	 * @param request
	 * @param response
	 * @return
	 */
	public static boolean removeCookie(String key,HttpServletRequest request,HttpServletResponse response){
		Cookie cookie = getCookie(key, request);
		if(cookie==null){
			return true;
		}
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		return true;
	}
}
